'''
Created on Jun 16, 2010

@author: oabalbin
'''
import os
import copy
import glob
import numpy as np
from RNAseq.common.ordereddict import OrderedDict
from collections import deque, defaultdict
from RNAseq.common.classes import myArray


def read_list_genes(inputfile):
    """
    Read panther gene list
    """
    genlist=defaultdict()
    for line in inputfile:        
        line = line.strip('\n')
        fields = line.split(';')
        #print fields 
        # To skip headers, star reading samples in column 7 of the file
        if fields[0][0] == '#': 
            continue                             
        if fields[0]=='':
            continue
        genlist[fields[1]] = fields[0]
    
    return genlist

    

def create_array4subset_genes(thisGeneArray, genelist):
    """
    Returns a sub-structure myArray using the genelist
    """
    notfound=[]
    new_gendict = defaultdict()
    new_genIntr = defaultdict()
    #common_genes = new_gene_set.intersection(set(thisGeneArray.gendict.values()))
    for i, gen in thisGeneArray.gendict.iteritems():
        try:
            genelist[gen]
            new_gendict[i] = gen
            new_genIntr[i] = thisGeneArray.genInterval[i]
        except KeyError:
            notfound.append(gen)
    
    newExpVal = thisGeneArray.expVal[new_gendict.keys(),:]
    newsampledict = copy.copy(thisGeneArray.sampledict)
    new_normalsamples = copy.copy(thisGeneArray.normal_samples)
    newGeneArray = myArray(newExpVal, new_gendict, newsampledict, new_normalsamples, new_genIntr)
    
    return newGeneArray

def create_thisGenearray(expression_matrix, gene_dictionary, sample_dictionary, normal_samples_list, gene_interval_dict):
    return myArray(expression_matrix, gene_dictionary, sample_dictionary, normal_samples_list, gene_interval_dict)
    


def get_gene_subset(thisgenelist, all_genes, all_gene_intervals):
        
    gene_subset = OrderedDict()
    gene_subset_int = OrderedDict()
    gene_subset_rows = OrderedDict()
    gene_array = deque()
    notfound=[]
    i=0
        
    for gen in thisgenelist:
        try:
            gene_rows = all_genes[gen]
            if not gene_rows:
                continue
            
            gene_interval = all_gene_intervals[gen]
            new_gene_rows=[] 
            
            for p,l in zip(gene_rows,gene_interval):
                gene_subset[i] = gen
                gene_subset_int[i] = l
                gene_array.append(p)
                new_gene_rows.append(i)
                i+=1 
            gene_subset_rows[gen] =  new_gene_rows
                
        except KeyError:
            notfound.append(gen)
    
    return gene_subset, np.array(gene_array), gene_subset_int, gene_subset_rows
  
def get_sample_subset(thissampleslist, all_samples):
        
    sample_subset = OrderedDict()
    sample_subset2 = OrderedDict()
    sample_array = deque()
    notfound=[]
    j=0
    for sp in thissampleslist:
        try:
            sample_array.append(all_samples[sp])
            sample_subset[j] = sp
            sample_subset2[sp] = j
            j+=1
        except KeyError:
            print 'sample not found ' + sp + str(j)
            notfound.append(sp)
    return sample_subset, np.array(sample_array), sample_subset2


def read_files_folder(folderpath,ext):
    ''' '''
    # Read files in folder
    myfiles=[]
    for infile in glob.glob( os.path.join(folderpath, '*'+ext) ):
        myfiles.append(infile)
        #print "current file is: " + infile
    return myfiles
